<?php
class SphinxQL{
	public $link;
	public $db_config = array ();
		
	//初始化类
	public function __construct($options) {
		$option = $this->__Config ($options);
		if (is_array ( $option )) {
			$this->db_config ['host'] = ($option ['host'] ? $option ['host'] : 'localhost');
			$this->db_config ['port'] = ($option ['port'] ? $option ['port'] : 9306);
			
			$this->link = $this->connect ();
			return $this;
		}
	}
	public function __Config($option = null){
		if ($option)
			return $option;
		else
			return $array();
	}
	//销毁类
	public function __destruct() {
		is_resource ( $this->link ) and mysql_close ( $this->link );
		unset($this);
	}
	
	//数据库连接函数
	public function connect() {
		if (is_resource ( $this->link ))
			return $this->link;
			
		extract ( $this->db_config ['connection'] );
		
		$connect = ($this->db_config ['persistent'] == TRUE) ? 'mysql_pconnect' : 'mysql_connect';
		$host = isset ( $host ) ? $host : $socket;
		$port = isset ( $port ) ? ':' . $port : '';
		if (($this->link = $connect ( $host . $port)) ) {
			return $this->link;
		}
		return FALSE;
	}
	public function exec($sql) {
		$array_result = array ();
		$result = mysql_query ( $sql, $this->link );
		if (stristr ( $sql, "select" )) {
			while ( @$row = mysql_fetch_assoc ( $result ) ) {
				array_push ( $array_result, $row );
			}
			return $array_result;
		}
		return $result;
	}
	public static function GetIDListByResult($res){
		//$Result = array ();
		if ($res ['matches']) {
			foreach ( $res ['matches'] as $Result ) {
				$id [] = $Result ['id'];
			}
			$idlist = implode ( ',', $id );
		}
		return $idlist;
	}
	public static function GetTotalCount($res){
		//$Result = array ();
		
		return $res['total_found'];
	}
	public function Query($keywords,$index,$limit = 10,$offset = 0,$sort='') {
		$this->Sphinx->SetLimits ( $offset, $limit);
		if($sort){
			$this->Sphinx->SetSortMode ( SPH_SORT_ATTR_DESC ,$sort);
		}
		$result = $this->Sphinx->Query ( $keywords, $index );
		$Data['IDList'] = $this->GetIDListByResult($result);
		$Data['TotalCount'] = $this->GetTotalCount($result);
 		return $Data;
	}
	
} 
